package web

import (
	"encoding/json"
	"goadmin-huasen-portal/util"
	kq "goadmin-huasen-portal/util/quequ"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/go-resty/resty/v2"
)

var (
	//HttpProxy     string
	//Limit         = 5
	KafkaLogsHttp kq.Kafka
)

func SendLogs(req *kq.HttpRequestLogEs) {
	bytes, _ := json.Marshal(req)
	if KafkaLogsHttp.Producer == nil {
		util.Log().Error("kafka 未配置")
		return
	}
	_ = KafkaLogsHttp.SendLogs(KafkaLogsHttp.Topic, string(bytes))
}

func Get(uri string, headers map[string]string) (*resty.Response, error) {
	// m := kq.HttpRequestLogEs{
	// 	Type:      "GET",
	// 	Url:       uri,
	// 	Proxy:     false,
	// 	Date:      time.Now().Format(time.DateOnly),
	// 	Time:      time.Now().Format(time.TimeOnly),
	// 	Timestamp: time.Now().Format("2006-01-02 15:04:05"),
	// }
	client := resty.New()
	client.SetRetryCount(3).
		AddRetryCondition(
			func(r *resty.Response, err error) bool {
				return r.StatusCode() == http.StatusTooManyRequests || err != nil
			},
		).
		SetTimeout(time.Second * 10)
	resp, err := client.R().
		//EnableTrace().
		SetHeaders(headers).
		Get(uri)
	if err != nil {
		util.Log().Error("重试次数耗尽: %v", err)
	}
	//SendLogs(&m)
	return resp, err
}

func Post(uri string, body any, isJson bool, headers map[string]string) (*resty.Response, error) {
	// b, _ := json.Marshal(body)
	// m := kq.HttpRequestLogEs{
	// 	Type:      "POST",
	// 	Url:       uri,
	// 	Body:      string(b),
	// 	Proxy:     false,
	// 	Date:      time.Now().Format(time.DateOnly),
	// 	Time:      time.Now().Format(time.TimeOnly),
	// 	Timestamp: time.Now().Format("2006-01-02 15:04:05"),
	// }

	client := resty.New()
	client.SetRetryCount(3).
		AddRetryCondition(
			func(r *resty.Response, err error) bool {
				return r.StatusCode() == http.StatusTooManyRequests || err != nil
			},
		).
		SetTimeout(time.Second * 10)
	if headers == nil {
		headers = map[string]string{}
	}
	if isJson {
		client.SetHeader("Content-Type", "application/json")
	} else {
		client.SetHeader("Content-Type", "application/x-www-form-urlencoded")
	}

	resp, err := client.R().
		SetHeaders(headers).
		SetBody(body).
		Post(uri)

	if err != nil {
		util.Log().Error("重试次数耗尽: %v", err)
	}
	//SendLogs(&m)
	return resp, err
}

func zhToUnicode(raw []byte) []byte {
	str, err := strconv.Unquote(strings.Replace(strconv.Quote(string(raw)), `\\u`, `\u`, -1))
	if err != nil {
		return nil
	}
	return []byte(str)
}
